package com.wzy.oa_sys.service.impl.user;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wzy.oa_sys.mapper.user.DeptMapper;
import com.wzy.oa_sys.mapper.user.UserMapper;
import com.wzy.oa_sys.model.pojo.user.OaDept;
import com.wzy.oa_sys.model.pojo.user.OaUser;
import com.wzy.oa_sys.model.request.user.DeptReq;
import com.wzy.oa_sys.model.response.user.DeptResp;
import com.wzy.oa_sys.service.user.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, OaDept> implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public List<DeptResp> getDeptList() {
        // 1. 从数据库获取所有部门信息
        List<OaDept> deptList = deptMapper.selectList(null);

        // 2. 创建一个用于存储返回对象的列表
        List<DeptResp> deptRespList = new ArrayList<>();

        // 3. 创建一个映射，方便通过 ID 查找每个部门
        Map<Long, DeptResp> deptMap = new HashMap<>();

        // 4. 循环遍历部门列表，填充 deptRespList 和 deptMap
        for (OaDept dept : deptList) {
            DeptResp deptResp = DeptResp.builder()
                    .id(dept.getNDeptId())
                    .deptname(dept.getCDeptName())
                    .address(dept.getCAddress())
                    .tel(dept.getCTel())
                    .email(dept.getCEmail())
                    .father(dept.getNFatherId() == 0 ? null : String.valueOf(dept.getNFatherId())) // 对应父级 ID
                    .build();

            deptRespList.add(deptResp);
            deptMap.put(dept.getNDeptId(), deptResp); // 将当前部门映射到其 ID
        }

        // 5. 创建一个列表用于存储最终的树形结构
        List<DeptResp> tree = new ArrayList<>();

        // 6. 构建树形结构
        for (DeptResp deptResp : deptRespList) {
            if (deptResp.getFather() == null) {
                tree.add(deptResp); // 父级为 null 的部门是根部门，添加到树中
            } else {
                // If father exists, find it and add the current dept's children to it
                DeptResp parentDept = deptMap.get(Long.parseLong(deptResp.getFather()));
                if (parentDept != null) {
                    // If the parent department's children is not initialized, create it
                    if (parentDept.getChildren() == null) {
                        parentDept.setChildren(new ArrayList<DeptResp>());
                    }
                    parentDept.getChildren().add(deptResp); // 将当前部门添加到其父部门的 children 列表中
                }
            }
        }
        // 7. 返回树形结构
        return tree;
    }

    @Override
    public List<DeptResp> getChildrens(){
        // 1. 从数据库获取所有部门信息
        List<OaDept> deptList = deptMapper.selectList(null);

        // 2. 创建一个用于存储返回对象的列表
        List<DeptResp> deptRespList = new ArrayList<>();

        // 3. 创建一个映射，方便通过 ID 查找每个部门
        Map<Long, DeptResp> deptMap = new HashMap<>();

        // 4. 循环遍历部门列表，填充 deptRespList 和 deptMap
        for (OaDept dept : deptList) {
            DeptResp deptResp = DeptResp.builder()
                    .deptname(dept.getCDeptName())
                    .father(dept.getNFatherId() == 0 ? null : String.valueOf(dept.getNFatherId())) // 对应父级 ID
                    .build();

            deptRespList.add(deptResp);
            deptMap.put(dept.getNDeptId(), deptResp); // 将当前部门映射到其 ID
        }

        // 5. 创建一个列表用于存储最终的树形结构
        List<DeptResp> tree = new ArrayList<>();

        // 6. 构建树形结构
        for (DeptResp deptResp : deptRespList) {
            if (deptResp.getFather() == null) {
                tree.add(deptResp); // 父级为 null 的部门是根部门，添加到树中
            } else {
                // If father exists, find it and add the current dept's children to it
                DeptResp parentDept = deptMap.get(Long.parseLong(deptResp.getFather()));
                if (parentDept != null) {
                    // If the parent department's children is not initialized, create it
                    if (parentDept.getChildren() == null) {
                        parentDept.setChildren(new ArrayList<DeptResp>());
                    }
                    parentDept.getChildren().add(deptResp); // 将当前部门添加到其父部门的 children 列表中
                }
            }
        }
        // 7. 返回树形结构
        return tree;
    }

    @Override
    public List<DeptResp> getAllDeptList() {
        List<OaDept> deptList = deptMapper.selectList(null);
        List<DeptResp> deptRespList = new ArrayList<>();
        deptList.forEach(dept -> {
            DeptResp build = DeptResp.builder()
                    .id(dept.getNDeptId())
                    .deptname(dept.getCDeptName())
                    .address(dept.getCAddress())
                    .tel(dept.getCTel())
                    .number(dept.getNNumber())
                    .hc(dept.getNHc())
                    .email(dept.getCEmail()).build();
            if(dept.getNFatherId() !=0){
                if(deptMapper.selectDeptById(dept.getNFatherId())!=null){
                    build.setFather(deptMapper.selectDeptById(dept.getNFatherId()).getCDeptName());
                }
            }
            if(userMapper.selectUserById(dept.getNManagerId())!=null){
                build.setAdmin(userMapper.selectUserById(dept.getNManagerId()).getCRealName());
            }
            if(dept.getNFatherId()!=0&&deptMapper.selectDeptById(dept.getNFatherId())!=null){
                build.setFather(deptMapper.selectDeptById(dept.getNFatherId()).getCDeptName());
            }
            deptRespList.add(build);
        });
        return deptRespList;
    }

    @Override
    public Boolean updateDept(DeptReq deptReq) {
        QueryWrapper<OaDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_dept_id",deptReq.getId());
        OaDept dept = deptMapper.selectOne(queryWrapper);
        if(deptReq.getDeptname()!=null&&deptReq.getDeptname()!=""){
            dept.setCDeptName(deptReq.getDeptname());
        }
        if(deptReq.getTel()!=null&&deptReq.getTel()!=""){
            dept.setCTel(deptReq.getTel());
        }
        if(deptReq.getParentDept().size() != 0){
            dept.setNFatherId(deptReq.getParentDept().get(deptReq.getParentDept().size()-1));
        }
        if(deptReq.getAddress()!=null&&deptReq.getAddress()!=""){
            dept.setCAddress(deptReq.getAddress());
        }
        if(deptReq.getEmail()!=null&&deptReq.getEmail()!=""){
            dept.setCEmail(deptReq.getEmail());
        }
        //更新admin
        if(deptReq.getAdmin()!=0){
            if(dept.getNManagerId()!=deptReq.getAdmin()){
                QueryWrapper<OaUser> queryWrapper2 = new QueryWrapper<>();
                queryWrapper2.eq("n_user_id",dept.getNManagerId());
                OaUser user = userMapper.selectOne(queryWrapper2);
                //更新原部门负责人
                if(user.getNRole()!=1){
                    user.setNRole(0);
                }
                user.setNDeptHead(0);
                userMapper.update(user,queryWrapper2);
                dept.setNManagerId(deptReq.getAdmin());
                QueryWrapper<OaUser> queryWrapper23 = new QueryWrapper<>();
                queryWrapper23.eq("n_user_id",deptReq.getAdmin());
                OaUser user1 = userMapper.selectOne(queryWrapper23);
                //更新新的部门部分人
                user1.setNRole(2);
                user1.setNDeptHead(1);
                user1.setNDeptId(deptReq.getId());
                userMapper.update(user1,queryWrapper23);
            }
        }
        if(deptReq.getHc()!=0){
            dept.setNHc(deptReq.getHc());
        }
        System.out.println(dept);
        int i = deptMapper.update(dept, queryWrapper);
        return true;
    }


    @Override
    public OaDept getDeptById(long deptId) {
        return deptMapper.selectDeptById(deptId);
    }

    @Override
    public void addDept(DeptReq deptReq) {
        OaDept dept = new OaDept();
        if(deptReq.getParentDept().size() != 0){
            dept.setNFatherId(deptReq.getParentDept().get(deptReq.getParentDept().size()-1));
        }
        dept.setCDeptName(deptReq.getDeptname());
        dept.setCAddress(deptReq.getAddress());
        dept.setCTel(deptReq.getTel());
        dept.setCEmail(deptReq.getEmail());
        dept.setNManagerId(deptReq.getAdmin());
        dept.setNHc(deptReq.getHc());
        int insert = deptMapper.insert(dept);
        if (insert > 0) {
            System.out.println("添加成功");
            QueryWrapper<OaDept> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("c_dept_name",deptReq.getDeptname());
            queryWrapper.eq("c_address",deptReq.getAddress());
            OaDept oaDept = deptMapper.selectOne(queryWrapper);
            QueryWrapper<OaUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.eq("n_user_id",deptReq.getAdmin());
            OaUser user = userMapper.selectOne(userQueryWrapper);
            user.setNDeptHead(1);
            user.setNRole(2);
            user.setNDeptId(oaDept.getNDeptId());
            userMapper.update(user,userQueryWrapper);
        } else {
            System.out.println("添加失败");
        }


    }

    @Override
    public int deleteDeptById(Integer id) {
        //没有删除方法，后续再添加
        int i = deptMapper.deleteDeptById(id);
        return i;
    }

    @Override
    public DeptResp getDeptById(Integer id) {
        QueryWrapper<OaDept> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("n_dept_id", id);
        OaDept dept = deptMapper.selectOne(queryWrapper);
        DeptResp deptResp = DeptResp.builder()
                .deptname(dept.getCDeptName())
                .address(dept.getCAddress())
                .tel(dept.getCTel())
                .email(dept.getCEmail())
                .number(dept.getNNumber())
                .hc(dept.getNHc())
                .build();
        if(dept.getNManagerId() != 0){
            OaUser oaUser = userMapper.selectUserById(dept.getNManagerId());
            deptResp.setAdmin(oaUser.getCRealName());
        }
        //上级
        if(dept.getNFatherId() != 0){
            OaDept oaDept = deptMapper.selectDeptById(dept.getNFatherId());
            deptResp.setFather(oaDept.getCDeptName());
        }
        return deptResp;
    }
}
